from concepts import *

from .elements import *


class GameDialog(Dialog):
    scenario = Attribute()
    gameset  = scenario._.gameset
    city     = scenario._.city
    map      = scenario._.map
    
    cache = Attribute(initiable = False, writable = True)
    
    def setup_elements(self):
        self.add_element('date_bar',       DateBar       (self, self.city.calendar))
        self.add_element('name_bar',       CityNameBar   (self, self.city))
        self.add_element('state_bar',      CityStateBar  (self, self.city))
        self.add_element('build_bar',      BuildBar      (self, self.city))
        self.add_element('build_panel',    BuildingsPanel(self, self.city, self.gameset, self.build_bar))
        self.add_element('selected_panel', SelectedPanel (self))
    
    def on_update(self):
        self.city.on_tick()
        
        new = None
        
        if self.build_panel.has_selection:
            if self.has_selected_area:
                new = (self.start_position,    self.selected_position)
            elif self.has_selected_tile:
                new = (self.selected_position, self.selected_position)
        
        if new != self.cache:
            self.city.clear_virtual()
            
            self.cache = new
            
            if new is not None:
                start, end = new
                
                for x in range(start.x, end.x + 1):
                    for y in range(start.y, end.y + 1):
                        self.city.place_virtual(self.build_panel.selection, Position(x, y))
    
    def on_map_selected(self, position):
        pass
    
    def on_map_clicked(self, position):
        if self.build_panel.has_selection:
            for building in self.city.virtual:
                self.city.build(building.type, building.position)
            
            self.city.clear_virtual()
        elif self.has_selected_tile and self.selected_tile.has_building:
            self.selected_panel.building = self.selected_tile.building
        else:
            self.center_view_on(position)
    
    def on_cancel(self):
        if self.build_panel.has_selection:
            self.build_panel.clear_selection()
        elif self.build_bar.has_action:
            self.build_bar.cancel_action()
        else:
            self.selected_panel.building = None
    
    def center_view_on(self, position):
        pass
    
    @property
    def selected_tile(self):
        if not self.has_selected_tile:
            return None
        else:
            return self.map.at(self.selected_position)
    
    @property
    def selected_position(self):
        pass

    @property
    def start_position(self):
        pass
    
    @property
    def has_selected_tile(self):
        pass
    
    @property
    def has_selected_area(self):
        pass
